import React, { useEffect, useState, useMemo } from 'react'
import { Avatar, Dropdown, message, Badge } from 'antd'
import type { MenuProps } from 'antd'
import { UserOutlined, DownOutlined, SearchOutlined } from '@ant-design/icons'
import styles from './index.module.less'
import { getFriendListApi, getFriendInfoApi } from '@/request/api/friend'
import { sourceUrl } from '@/config/baseConfig'

//
//
export default function DialogList({
  chatUsersList,
  setCurrentChatUserId,
  currentChatUsertId,
}: {
  chatUsersList: localChatUsersItf[]
  setCurrentChatUserId: Function
  currentChatUsertId: string
}) {
  useEffect(() => {
    if (chatUsersList.length === 0) return
    setMessageBoxList([...chatUsersList])
  }, [chatUsersList])

  // 声明一个变量messageBoxList，用于存储消息框列表
  const [messageBoxList, setMessageBoxList] = useState<localChatUsersItf[]>([])

  // 当前拖动的数组元素下标
  const [currnetDragIndex, setCurrentDragIndex] = useState<number>(null)
  // 要放置的数组位置下标
  const [dropPositionIndex, setDropPositionIndex] = useState<number>(null)

  // 放置时改变位置
  const dropHandler = () => {
    let array = [...messageBoxList]
    const val = messageBoxList[currnetDragIndex]

    // 将数组中指定的元素移动到另一个位置。
    // 删除数组指定下标元素；将一个值插入到数组指定下标
    array.splice(currnetDragIndex, 1)
    array.splice(dropPositionIndex, 0, val)
    setMessageBoxList([...array])
  }

  return (
    <div className={styles.dialogList}>
      {/* 好友tab栏 */}
      <div className={styles.friendTab}>
        <div>
          <DropComponent
            label={'follows'}
            type={0}
            setChatUserId={setCurrentChatUserId}
          />
        </div>

        <div>
          <DropComponent
            label={'fans'}
            type={1}
            setChatUserId={setCurrentChatUserId}
          />
        </div>

        <div>
          <SearchOutlined />
        </div>
      </div>

      {/* 消息盒子列表 */}
      {messageBoxList.map((item, index) => {
        return (
          <MessageBox
            key={item.chatUserId}
            boxInfo={item}
            index={index}
            getDragIndex={setCurrentDragIndex}
            getDropIndex={setDropPositionIndex}
            dropHandler={dropHandler}
            setChatUserId={setCurrentChatUserId}
            currentChatUserId={currentChatUsertId}
          />
        )
      })}
    </div>
  )
}

//
// 下拉框组件
function DropComponent({
  label,
  type,
  setChatUserId,
}: {
  label: string
  type: 0 | 1
  setChatUserId: Function
}) {
  const [items, setItems] = useState<MenuProps['items']>([])

  // 下拉菜单项格式处理函数
  const menuHandler = (
    list: getFriendResultItf[],
    type: 0 | 1
  ): MenuProps['items'] => {
    const arr = list.map((item) => {
      return {
        key: item.id,
        label: (
          <FriendComponent
            userInfo={item}
            type={type}
            setChatUserId={setChatUserId}
          />
        ),
      }
    })
    return arr
  }

  // 获取好友列表，0 我关注的好友， 1 关注我的粉丝好友
  const getFriendList = async (type: 0 | 1) => {
    let page = 1
    let friendList: getFriendResultItf[] = []

    const fn = async () => {
      const params = { type: type, page: page, pageSize: 20 }
      const res = await getFriendListApi(params)

      if (res.code !== 200) return message.error('获取好友列表出错！')
      friendList = [...friendList, ...res.data.records]

      if (friendList.length >= res.data.total) return
      page++
      await fn()
    }

    await fn()
    // handler([...friendList])

    setItems([...menuHandler(friendList, type)])
  }

  return (
    <Dropdown
      trigger={['click']}
      onOpenChange={(open) => {
        open ? getFriendList(type) : null
      }}
      menu={{ items }}
    >
      <div
        style={{
          padding: '10px 5px',
          width: '100%',
          display: 'flex',
          justifyContent: 'space-around',
        }}
        onClick={(e) => e.preventDefault()}
      >
        {label} <DownOutlined style={{ fontSize: '14px' }} />
      </div>
    </Dropdown>
  )

  //
  // 好友信息组件
  function FriendComponent({
    userInfo = null,
    type,
    setChatUserId,
  }: {
    userInfo: getFriendResultItf
    type: 1 | 0
    setChatUserId: Function
  }) {
    const styleone = {
      padding: '6px 6px',
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      cursor: 'pointer',
      borderBottom: '2px solid white',
      minWidth: '120px',
    }
    const styletwo = {
      fontSize: '14px',
      fontWeight: 'bold',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      // whiteSpace: 'nowrap',
      width: '80px',
    }

    const [userId, sestUserId] = useState('')
    const [avatar, setAvatar] = useState('')
    const [nickname, setNickname] = useState('')

    useEffect(() => {
      if (!userInfo) return
      if (type === 1) {
        const { masterId, masterNickname, masterAvatar } = userInfo
        sestUserId(masterId)
        setAvatar(masterAvatar)
        setNickname(masterNickname)
      }
      if (type === 0) {
        const { friendId, friendNickname, friendAvatar } = userInfo
        sestUserId(friendId)
        setAvatar(friendAvatar)
        setNickname(friendNickname)
      }
    }, [])

    return (
      <div style={styleone} onClick={() => setChatUserId(userId)}>
        <Avatar src={sourceUrl + avatar} size={32} icon={<UserOutlined />} />
        <div style={styletwo}>{nickname}</div>
      </div>
    )
  }
}

//
// 消息盒子
interface MessageBoxProps {
  boxInfo: localChatUsersItf
  index: number
  getDragIndex: Function
  getDropIndex: Function
  dropHandler: Function
  setChatUserId: Function
  currentChatUserId: string
}
function MessageBox(props: MessageBoxProps) {
  const {
    boxInfo,
    index,
    getDragIndex,
    getDropIndex,
    dropHandler,
    setChatUserId,
    currentChatUserId,
  } = props

  // 在数组中的序号
  const [serial, setSerial] = useState<number>()
  //是否半透明
  const [halfOpacity, setHalfOpacity] = useState<boolean>(false)

  useEffect(() => {
    setSerial(index)
    setHalfOpacity(false)
  }, [index])

  // 放置到何处(移入放置区)
  const dragOver = (index: number, event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault()
    getDropIndex(index)
    setHalfOpacity(true)
  }

  const { record, notCount, chatUserId, createTime, avatar, nickname } = boxInfo

  const formattedDate = useMemo(() => {
    // 将 Unix 时间戳转换为毫秒
    const date = new Date(Number(createTime))
    // 获取年、月、日
    const year = date.getFullYear().toString().slice(2) // 取年份的最后两位
    const month = (date.getMonth() + 1).toString().padStart(2, '0') // 月份从0开始，加1后补零
    const day = date.getDate().toString().padStart(2, '0') // 补零
    // 拼接成日期字符串
    return `${year}/${month}/${day}`
  }, [createTime])

  return (
    <div
      className={styles.messageBox}
      draggable
      onDrop={() => dropHandler()}
      onDragStart={() => getDragIndex(serial)}
      onDragLeave={() => setHalfOpacity(false)}
      onDragEnd={() => setHalfOpacity(false)}
      onDragOver={(event) => dragOver(serial, event)}
      onClick={() => setChatUserId(chatUserId)}
      style={{
        opacity: halfOpacity ? 0.5 : 1,
        backgroundColor: currentChatUserId === chatUserId ? '#F0F2F5' : '',
      }}
    >
      <div className={styles.avatar}>
        <Avatar
          src={sourceUrl + avatar}
          shape="square"
          size={52}
          icon={<UserOutlined />}
        />
      </div>

      <div className={styles.detail}>
        <div className={styles.nickname}>
          <div>{nickname}</div> <div>{formattedDate}</div>
        </div>
        <div className={styles.message}>
          <div>{record?.message ? record.message : ''}</div>
          <Badge count={notCount > 0 ? notCount : 0} />
        </div>
      </div>
    </div>
  )
}
